//
// Created by kevin on 2020/7/13.
//

#ifndef SRC_ADC_H
#define SRC_ADC_H
#include "wtr_usb2ros/common_include.h"
namespace wtr{

    class ADC{
        /**
        * @brief 通信基本参数
        * @param None
        * @retval None
        */
        int ADC_Data[10];
        int DevHandle;
        int CANIndex;
        int type;
        bool isDJIFdb;
        int ADC_NUMS;
        char ADC_Channel = 0x01;//使能ADC_CH0和ADC_CH1

        short Buffer[40960];
//计算一个整数bit位为1的个数
        uint32_t BitCount(uint32_t data)
        {
            uint32_t count=0;
            while(data){
                count++;
                data&=(data-1);
            }
            return count;
        }
    public:
        ADC(){
            ADC_NUMS  = 1;
            ADC_Channel = 0x03;
        }
        ADC(char ADC_CHA){
            ADC_Channel = ADC_CHA;
            ADC_NUMS  = 10;
        }
        void setDevHandle(int DevHand){
            DevHandle = DevHand;
            int ret;
            //初始化ADC
            ret = ADC_Init(DevHandle,ADC_Channel,1000000);
            if(ret != ADC_SUCCESS){
                LOG(FATAL)<<"Init adc error!";
            }
        }
        void readADC(){

                int ret;
                //手动读取ADC数据
                ret = ADC_Read(DevHandle, Buffer, ADC_NUMS);
                if (ret != ADC_SUCCESS) {
                    LOG(FATAL)<<"Read adc error!";
                } else {
                    int num_chan = BitCount(ADC_Channel);
                    ADC_Data[0] = 0;
                    ADC_Data[1] = 0;
                    for(int j = 0 ; j < ADC_NUMS ; j ++){
                        ADC_Data[0]+= Buffer[ j*2];
                        ADC_Data[1]+= Buffer[ 2*j+1];
                    }
                    ADC_Data[0]/=ADC_NUMS;
                    ADC_Data[1]/=ADC_NUMS;

                    LOG(INFO)<<num_chan<<" "<<ADC_Data[0]<<" "<< ADC_Data[1]<<" "<<ADC_Data[2];
                }


        }

    public:
        float * getPotentio()
        {
            float pot[2];
            float* pot_ptr;
            pot[0] = ADC_Data[0];
            pot[1] = ADC_Data[1];
            pot_ptr = pot;

            return pot_ptr;
        }
    };

}

#endif //SRC_ADC_H
